package com.lifeng.zk.zkclient.lock;

import org.I0Itec.zkclient.ZkClient;


/**
 * Created by lifeng on 2018/6/14.
 * 模拟并发获取锁分布式锁
 */
public class LockTest{

    public static void main(String[] args) throws Exception{
        ZkClient zkClient = new ZkClient("127.0.0.1:2181");
        SimpleDistributedLock simple = new SimpleDistributedLock(zkClient, "/locker");
        for (int i = 0; i < 100; i++) {
            try {
                LockThread test = new LockThread(simple);
                test.start();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
class LockThread extends Thread{
    SimpleDistributedLock simple;
    public LockThread(SimpleDistributedLock simple){
        this.simple = simple;
    }

    @Override
    public void run() {
        try {
            System.out.println("正在获取锁:" + System.currentTimeMillis());
            simple.acquire();
            Thread.sleep(100);
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            try {
                simple.release();
                System.out.println("释放了锁");
            } catch (Exception e) {
                e.printStackTrace();
                System.out.println("没有获取到锁");
            }
            System.out.println("=================\r\n");
        }
    }
}
